﻿namespace Sai.Test.TestDataBuilders
{
	using System.Collections.Generic;
	using System.Text;

	public class CompilableCodeBuilder : IBuildable
	{
		private List<string> usings = new List<string>();
		private string namespaceName;
		private List<IBuildable> typeBuilders = new List<IBuildable>();

		public static CompilableCodeBuilder CompilableCode()
		{
			return new CompilableCodeBuilder();
		}

		public CompilableCodeBuilder UsingNamespace(string usingReference)
		{
			this.usings.Add(usingReference);

			return this;
		}

		public CompilableCodeBuilder UsingDefaultNamespaces()
		{
			this.usings.Add("System");
			this.usings.Add("System.Collections.Generic");
			this.usings.Add("System.Text");

			return this;
		}

		public CompilableCodeBuilder HasNamespace(string namespaceName)
		{
			this.namespaceName = namespaceName;

			return this;
		}

		public CompilableCodeBuilder Includes(IBuildable builder)
		{
            this.typeBuilders.Add(builder);

			return this;
		}

		public string Build()
		{
			var builder = new StringBuilder();

			foreach (var u in this.usings)
			{
				builder.AppendFormat("using {0};", u);
				builder.AppendLine();
			}

			builder.AppendLine();

			builder.AppendFormat("namespace {0}", this.namespaceName);
			builder.AppendLine();
			builder.AppendLine("{");

			foreach (var tb in this.typeBuilders)
			{
                builder.AppendLine(tb.Build());
				builder.AppendLine();
			}

			builder.AppendLine("}"); // end of namespace

			return builder.ToString();
		}
	}
}
